//
//  SchoolViewController.m
//  Edumap
//
//  Created by 刘建峰 on 16/7/18.
//  Copyright © 2016年 yuf. All rights reserved.
//

#import "SchoolViewController.h"
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>
#import <CoreLocation/CLLocationManagerDelegate.h>
#import "MessageCenterViewController.h"
#import "SchoolLayout.h"
#import "SchoolLeftCollectionViewCell.h"
#import "SchoolRightCollectionViewCell.h"
#import "SchoolProfileViewController.h"
#import "ListUniversitiesViewController.h"
#import "AdverDetailViewController.h"

static NSString *cellIdentifier = @"SchoolLeftCollectionViewCell";
static NSString *CellIdentifier = @"SchoolRightCollectionViewCell";

@interface SchoolViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,BestScrollViewDelegate,BestScrollViewDatasource,UIScrollViewDelegate,UITextFieldDelegate,CLLocationManagerDelegate,UIAlertViewDelegate>{
    NSInteger _totle;
}
@property (nonatomic,assign)   NSInteger    pageNO;
@property (strong, nonatomic) IBOutlet UIView *navView;

@property (strong, nonatomic) IBOutlet UIButton *regionButton;
@property (strong, nonatomic) IBOutlet UILabel *regionLabl;
@property(nonatomic,strong)CLLocationManager * locationManger;

@property (strong, nonatomic) IBOutlet UIButton *messageNumberButton;
@property (strong, nonatomic) IBOutlet UILabel *messageNumberLabel;
@property (strong, nonatomic) IBOutlet UILabel *BGlabel;
@property (strong, nonatomic) IBOutlet UITextField *textField;
@property (strong, nonatomic) IBOutlet UIScrollView *scroview;
@property (strong, nonatomic) IBOutlet UICollectionView *collectionView;
@property (nonatomic,strong)  BestScrollView *headerScroll;//滚动栏
@property(nonatomic,strong)SchoolLayout * flowLayout;
@property (nonatomic,strong)  NSMutableArray  *imageArray;
@property(nonatomic,strong)NSMutableArray * schoolArray;
@property(nonatomic,strong)NSMutableArray * SchoolClassesArray;
@property(nonatomic,assign)CGFloat offSet;


@end

@implementation SchoolViewController

- (void)viewWillAppear:(BOOL)animated{
   
    if ([Common getLoginStatus]) {
        _messageNumberLabel.hidden = YES;
        [self getnoticeNum];
        
    } else {
        _messageNumberLabel.hidden = YES;
    }
    [self SchoolClasses];
    [self getAdvertiseBanner];
    _regionLabl.text = [[NSUserDefaults standardUserDefaults]objectForKey:@"cityName"];

}

- (void)viewDidLoad {
    [super viewDidLoad];

    _imageArray = [NSMutableArray array];
    _pageNO = 1;
    _schoolArray = [NSMutableArray array];
    [self initViewLayout];
  
    [self addRefreshing];
}

- (void)initViewLayout{
    [self adaptiveViewLayout:self.view];
    [self adaptiveViewLayout:self.navView];
    [self adaptiveViewLayout:self.scroview];
    _scroview.frame = CGRectMake(0, 64*VerticalRatio(), 320*VerticalRatio(), 504*VerticalRatio()-49);
    _scroview.contentSize = flexibleSize(CGSizeMake(0, 716), NO);
    _scroview.delegate = self;
//    
    _collectionView.frame = CGRectMake(0, 261*VerticalRatio(), 320*VerticalRatio(), CGRectGetHeight(_collectionView.frame)-49);
    
    self.messageNumberLabel.layer.masksToBounds = YES;
    self.messageNumberLabel.layer.cornerRadius = 7*VerticalRatio();
    self.BGlabel.layer.masksToBounds = YES;
    self.BGlabel.layer.cornerRadius = 4*VerticalRatio();
    _textField.delegate = self;
    
    //广告栏
    _headerScroll=[[BestScrollView alloc]  initWithFrame:flexibleFrame(CGRectMake(0, 0, 320, 160), NO)];
    [self.scroview addSubview:_headerScroll];
    
    _flowLayout =[[SchoolLayout alloc]init];
    _flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    _flowLayout.minimumInteritemSpacing = 0;
    _flowLayout.minimumLineSpacing = 0;
    self.collectionView.collectionViewLayout = _flowLayout;
    self.collectionView.userInteractionEnabled=YES;
    [self.collectionView registerNib:[UINib nibWithNibName:cellIdentifier bundle:nil] forCellWithReuseIdentifier:cellIdentifier];
    [self.collectionView registerNib:[UINib nibWithNibName:CellIdentifier bundle:nil] forCellWithReuseIdentifier:CellIdentifier];
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    
    self.collectionView.backgroundColor = [UIColor whiteColor];
    
}
#pragma mark - 重新定位
- (IBAction)reLocation:(id)sender {
   UIAlertView * alertView = [[UIAlertView alloc]initWithTitle:@"" message:@"是否请求定位?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alertView show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 1) {
        [self startLocation];
    }
}

#pragma mark - 消息
- (IBAction)message:(id)sender {
    if (![Common getLoginStatus]) {
        [[AppDelegate sharedAppDelegate]ShowLoginPage];
        return;
    }
    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"TeachStoryboard" bundle:nil];
    MessageCenterViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"MessageCenter"];
    page.unReadNum = [_messageNumberLabel.text integerValue];
    [[Common getNavigation] pushViewController:page];
}
#pragma mark - 初中 && 高中 && 大学
- (IBAction)phase:(UIButton *)sender {
    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"SchoolStoryboard" bundle:nil];
    ListUniversitiesViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"ListUniversities"];
    if (sender.tag == 100) {
        //初中
        for (int i = 0; i < _SchoolClassesArray.count; i++) {
            NSString *msdtName = [NSString stringWithFormat:@"%@",_SchoolClassesArray[i][@"msdtName"]];
            if ([msdtName isEqualToString:@"初中"]) {
                page.msdtId = [NSString stringWithFormat:@"%@",_SchoolClassesArray[i][@"msdtId"]];
                [[Common getNavigation] pushViewController:page];
            }
        }
    } else if (sender.tag == 101) {
        //高中
        for (int i = 0; i < _SchoolClassesArray.count; i++) {
            NSString *mlagName = [NSString stringWithFormat:@"%@",_SchoolClassesArray[i][@"msdtName"]];
            if ([mlagName isEqualToString:@"高中"]) {
                page.msdtId = [NSString stringWithFormat:@"%@",_SchoolClassesArray[i][@"msdtId"]];
                [[Common getNavigation] pushViewController:page];
            }
        }
    } else if (sender.tag == 102) {
        //大学
        for (NSInteger i = 0; i < _SchoolClassesArray.count; i++) {
            NSString *mlagName = [NSString stringWithFormat:@"%@",_SchoolClassesArray[i][@"msdtName"]];
            if ([mlagName isEqualToString:@"大学"]) {
                page.msdtId = [NSString stringWithFormat:@"%@",_SchoolClassesArray[i][@"msdtId"]];
                [[Common getNavigation] pushViewController:page];
            }
        }
    }
}

#pragma mark - 获取学校类别
-(void)SchoolClasses{
    
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:JY_mallStoreDevelperTypeList withHttpType:@"POST" withTag:JY_JY_mallStoreDevelperTypeList];
}

#pragma mark  获取首页广告BANNER--=========================================
-(void)getAdvertiseBanner{
    
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:@"1" forKey:@"Id"];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:JY_queryAdvertismentById withHttpType:@"POST" withTag:JY_JY_queryAdvertismentById];
}


#pragma mark === 获取未读信息数量
- (void)getnoticeNum{

    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"museId"];
    [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"msceMemberId"];
    [dic setObject:[Common getLoginInfo][Key_User_password] forKey:@"musePwd"];
    [dic setObject:[Common getLoginInfo][Key_User_onlineKey] forKey:@"museOnlineTag"];
    
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:JY_unreadInformation withHttpType:@"POST" withTag:JY_JY_unreadInformation];
}

#pragma mark -- 添加刷新数据
- (void)addRefreshing{
    self.scroview.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        int64_t delayInSeconds = 8.0;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [self.scroview.header endRefreshing];
        });
        self.pageNO = 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求订单数据
            [self getSchoolList];
        });
        
    }];
    // 马上进入刷新状态
    [self.scroview.header beginRefreshing];
}
//加载更多数据
- (void)loadMoreData{
    if (self.schoolArray.count == _totle) {
        [self.collectionView.footer endRefreshing];
    }else{
        self.pageNO = self.pageNO + 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求订单数据
            [self getSchoolList];
        });
    }
    
}


#pragma mark === 推荐学校列表
- (void)getSchoolList{
   
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];

    [dic setObject:[NSNumber numberWithInteger:_pageNO] forKey:@"page"];
    [dic setObject:[NSNumber numberWithInteger:PageSize] forKey:@"pageSize"];
    [dic setObject:@"1" forKey:@"msdeIsRecommend"];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:JY_mallStoreDeveloperRecommendList withHttpType:@"POST" withTag:JY_JY_mallStoreDeveloperRecommendList];
    
}



#pragma mark ==== UITextFieldDelegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self hideKeyBoard];
    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"SchoolStoryboard" bundle:nil];
    ListUniversitiesViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"ListUniversities"];
    page.serachStr = _textField.text;
    [[Common getNavigation] pushViewController:page];
    return YES;
}

#pragma mark -- coreLocation

- (void)startLocation{
    
    // 判断定位操作是否被允许
    
    if([CLLocationManager locationServicesEnabled]) {
        
        _locationManger = [[CLLocationManager alloc] init];
        _locationManger.delegate = self;
        _locationManger.desiredAccuracy = kCLLocationAccuracyBest;
        _locationManger.distanceFilter = 5.0f;
        // 总是授权
        [_locationManger requestAlwaysAuthorization];
        if ([[[UIDevice currentDevice] systemVersion] floatValue]>=8) {
            [_locationManger requestWhenInUseAuthorization];//使用程序其间允许访问位置数据（iOS8定位需要）
            [_locationManger requestAlwaysAuthorization];
        }
        [_locationManger startUpdatingLocation];
        
        
    }else {
        
        //提示用户无法进行定位操作
        
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"定位不成功 ,请确认开启定位" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        
        [alertView show];
        
    }
    // 开始定位
    [_locationManger startUpdatingLocation];
}


- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
    CLGeocoder * geoCoder = [[CLGeocoder alloc] init];
    [geoCoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *placemarks, NSError *error) {
        for (CLPlacemark * placemark in placemarks) {
            
            NSDictionary *test = [placemark addressDictionary];
            //  Country(国家)  State(城市)  SubLocality(区)
            NSString * cityName = test[@"SubLocality"];
            _regionLabl.text = cityName;
            [[NSUserDefaults standardUserDefaults]setObject:cityName forKey:@"cityName"];
        }
    }];
    [_locationManger stopUpdatingLocation];
}


#pragma mark  ==== scroViewDelegate

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    if (scrollView == _collectionView || scrollView== _scroview) {
        _offSet = scrollView.contentOffset.y;
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    if (scrollView == _collectionView || scrollView == _scroview ) {
        if (scrollView.contentOffset.y>_offSet) {
            
            [_scroview setContentOffset:CGPointMake(0, 261*VerticalRatio()) animated:YES];
            if(_collectionView.contentSize.height>_collectionView.frame.size.height){
                _scroview.scrollEnabled = NO;
            }
            _collectionView.scrollEnabled = YES;
        }else{
            if (scrollView == _scroview) {
                [_scroview setContentOffset:CGPointMake(0, 0) animated:YES];
                _scroview.scrollEnabled = YES;
                _collectionView.scrollEnabled = NO;
            }else{
                if (decelerate == YES) {
                    [_scroview setContentOffset:CGPointMake(0, 0) animated:YES];
                    _scroview.scrollEnabled = YES;
                    _collectionView.scrollEnabled = NO;
                }
            }
            
        }
    }
}


#pragma  mark BestView Delegate Data=source=====================


- (NSInteger)numberOfPages
{
    
    return  self.imageArray.count;
    
}

- (UIView *)pageAtIndex:(NSInteger)index
{
    
    if (self.imageArray.count>0) {
        
        UIImageView  *imageView=[[UIImageView alloc]  initWithFrame: flexibleFrame(CGRectMake(0, 0, 320, 160), NO)];
        [imageView  sd_setImageWithURL:[NSURL URLWithString: [NSString stringWithFormat:@"%@%@",IP_Address_ImageDown_Fresh,_imageArray[index][@"titleimg"]]] placeholderImage:[UIImage imageNamed:@"school1"]];
        return imageView;
    }
    return nil;
}


- (void)didClickPage:(BestScrollView *)csView atIndex:(NSInteger)index
{
    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"SchoolStoryboard" bundle:nil];
    AdverDetailViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"AdverDetail"];
    page.adverId = [NSString stringWithFormat:@"%@",_imageArray[index][@"id"]];
    [[Common getNavigation] pushViewController:page];
}

#pragma mark -- UICollectionViewDataSource
//定义展示的UICollectionViewCell的个数
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return _schoolArray.count;
    
}
//定义展示的Section的个数
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

//定义每个UICollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
      if (indexPath.row%2 == 0) {
          return CGSizeMake(158*VerticalRatio(), 178*VerticalRatio());
    }else{
        return CGSizeMake(158*VerticalRatio(), 208*VerticalRatio());
    }
}
//定义每个UICollectionView 的 margin
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(0,0, 0, 0);
    
}
//每个UICollectionView展示的内容
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary * dic = _schoolArray[indexPath.row];
    
    if (indexPath.row%2 == 0) {
       SchoolLeftCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
        NSString * image = [NSString stringWithFormat:@"%@",dic[@"msdeImage"]];
        if (image.length>0) {
            [cell.schoolImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IP_Address_ImageDown_Fresh,image]]];
        }
        cell.schoolName.text = [NSString stringWithFormat:@"%@",dic[@"msdeName"]];
        return cell;
    }else{
        SchoolRightCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
        NSString * image = [NSString stringWithFormat:@"%@",dic[@"msdeImage"]];
        if (image.length>0) {
            [cell.schoolImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IP_Address_ImageDown_Fresh,image]]];
        }
        cell.schoolName.text = [NSString stringWithFormat:@"%@",dic[@"msdeName"]];
        return cell;
    }
    
    return nil;
    
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"SchoolStoryboard" bundle:nil];
    SchoolProfileViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"SchoolProfile"];
    page.schoolId = _schoolArray[indexPath.row][@"msdeId"];
    page.backBlock = ^(){};
    [[Common getNavigation] pushViewController:page];
   
    
}





#pragma   mark---- GetADBanner Request Delegate

-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{
    [_scroview.header endRefreshing];
    [_collectionView.footer endRefreshing];
    if (tag==JY_JY_unreadInformation) {
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else {
            _messageNumberLabel.text = [NSString stringWithFormat:@"%@",database[@"result"][@"noReadNum"]];
            _messageNumberLabel.hidden = NO;
            if ([_messageNumberLabel.text isEqualToString:@"0"]) {
                _messageNumberLabel.hidden = YES;
            }
        }
    
    }else if (tag == JY_JY_queryAdvertismentById){
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else {
        self.imageArray = database[@"result"];
            if (_imageArray.count>0) {
                self.headerScroll.delegate=self;
                self.headerScroll.datasource=self;
                [self.headerScroll showImageArray:self.imageArray   withAnimation:YES];
            }
        }
    }else if(tag == JY_JY_mallStoreDeveloperRecommendList){
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else {
            dispatch_async(dispatch_get_main_queue(), ^{
                _totle = [database[@"result"][@"total"] integerValue];
                if (_totle > PageSize) {
                    __weak __typeof(self) weakSelf = self;
                    if (!self.collectionView.footer) {
                        // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
                        self.collectionView.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
                            [weakSelf loadMoreData];
                        }];
                    }
                }
                if (self.pageNO == 1) {
                    [self.schoolArray removeAllObjects];
                }
                NSArray *arr = database[@"result"][@"rows"];
                for (id entity in arr) {
                    [self.schoolArray addObject:entity];
                }
                _flowLayout.itemCount = _schoolArray.count;
                [_collectionView reloadData];
                
            });

        }
    } else if(tag == JY_JY_mallStoreDevelperTypeList){
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else {
            self.SchoolClassesArray = database[@"result"];
        }
    }
    
}

-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{
    [_scroview.header endRefreshing];
    [_collectionView.footer endRefreshing];
    [self dismissWaitDialog];
}



@end
